import { useRef, useState } from "react";
import { userUpdateAvatarApi } from "../../http/module/User";
export default function UserCard({ user, onUploadAvatar }) {
  const fileInputRef = useRef(null);
  const [preview, setPreview] = useState(user.avatar);
  const [loading, setLoading] = useState(false);
  const [uploadSuccess, setUploadSuccess] = useState(false);
  const [uploadError, setUploadError] = useState(null);

  const handleClickAvatar = () => {
    fileInputRef.current.click();
  };

  const handleImageChange = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith("image/")) {
      setUploadError("请选择一张图片文件");
      return;
    }

    // 本地预览（Base64）
    const reader = new FileReader();
    reader.onloadend = async () => {
      const base64Image = reader.result;
      console.log(base64Image);

      setPreview(base64Image);
      setUploadError(null);
      setUploadSuccess(false);
      setLoading(true);

      try {
        await uploadFileToServer(file);
        onUploadAvatar?.(file);
        setUploadSuccess(true);
      } catch (error) {
        setUploadError("上传失败，请稍后再试", error);
      } finally {
        setLoading(false);
      }
    };

    reader.readAsDataURL(file);
  };

  // 真正上传 file 的函数
  const uploadFileToServer = async (file) => {
    const formData = new FormData();
    formData.append("file", file);
    const response = await userUpdateAvatarApi(formData);
  };

  return (
    <div className="border border-gray-200 p-6 rounded-lg hover:shadow-lg transition bg-white max-w-xs mx-auto">
      <div className="grid grid-cols-1 gap-4">
        {/* Avatar */}
        <div className="flex justify-center relative">
          <div
            onClick={handleClickAvatar}
            className="cursor-pointer hover:opacity-80 transition relative"
            title="点击更换头像"
          >
            <img
              src={preview}
              alt="User Avatar"
              className="w-24 h-24 rounded-full border-4 border-gray-100 shadow-md object-cover"
            />
            {loading && (
              <div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-60 rounded-full">
                <svg
                  className="w-6 h-6 text-blue-500 animate-spin"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  ></circle>
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8v8H4z"
                  ></path>
                </svg>
              </div>
            )}
          </div>
          <input
            type="file"
            accept="image/*"
            className="hidden"
            ref={fileInputRef}
            onChange={handleImageChange}
          />
        </div>

        {/* 用户名 */}
        <h2 className="text-xl font-semibold text-gray-900 text-center mt-2">
          {user.username}
        </h2>

        {/* 上传提示 */}
        {uploadSuccess && (
          <p className="text-green-600 text-sm text-center">头像上传成功！</p>
        )}
        {uploadError && (
          <p className="text-red-500 text-sm text-center">{uploadError}</p>
        )}

        {/* 用户数据 */}
        <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-center text-gray-700 mt-4">
          <div className="flex flex-col items-center">
            <span className="text-lg font-semibold text-gray-800">
              {user.totalFans}
            </span>
            <span className="text-sm text-gray-500">Fans</span>
          </div>
          <div className="flex flex-col items-center">
            <span className="text-lg font-semibold text-gray-800">
              {user.totalGetLikes}
            </span>
            <span className="text-sm text-gray-500">Likes</span>
          </div>
          <div className="flex flex-col items-center">
            <span className="text-lg font-semibold text-gray-800">
              {user.totalQuestions}
            </span>
            <span className="text-sm text-gray-500">Questions</span>
          </div>
          <div className="flex flex-col items-center">
            <span className="text-lg font-semibold text-gray-800">
              {user.totalAnswers}
            </span>
            <span className="text-sm text-gray-500">Answers</span>
          </div>
        </div>
      </div>
    </div>
  );
}
